package com.sugar.rpc.server.handler;

import com.sugar.rpc.common.model.RpcRequest;
import com.sugar.rpc.common.model.RpcResponse;
import com.sugar.rpc.common.registry.RpcServiceRegistry;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

// server/RpcHandler.java
public class RpcHandler extends SimpleChannelInboundHandler<RpcRequest> {

    private final RpcServiceRegistry registry;

    public RpcHandler(RpcServiceRegistry registry) {
        this.registry = registry;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest req) throws Exception {
        RpcResponse response = new RpcResponse();
        try {
            Object service = registry.getService(req.getInterfaceName());
            Method method = service.getClass().getMethod(req.getMethodName(), req.getParamTypes());
            Object result = method.invoke(service, req.getArgs());
            response.setResult(result);
        } catch (Exception e) {
            response.setError(e.getMessage());
        }
        ctx.writeAndFlush(response);
    }
}

